#include <iostream>
using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode():val(0),next(nullptr){
    }
    ListNode(int x):val(x),next(nullptr){}
    ListNode(int x,ListNode *next):val(x),next(next){}
};
class Solution {
public:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head= nullptr,*tail= nullptr;
        int carry=0;
        while(l1||l2){
            int x1=l1?l1->val:0;
            int x2=l2?l2->val:0;
            int sum=x1+x2+carry;
            if(!head){
                tail=new ListNode(sum%10);
               head=tail;
            }
            else{
                tail->next=new ListNode(sum%10);
                tail=tail->next;
            }
            if(l1){
                l1=l1->next;
            }
            if(l2){
                l2=l2->next;
            }
            carry=sum/10;
        }
        if(carry>0){
            tail->next=new ListNode(carry);
        }
        return head;
    }
};
int main(){
    ListNode *l1= nullptr;
    ListNode *l2= nullptr;
    ListNode p1(2);
    ListNode p2(3);
    l1=new ListNode(2);
    l2=new ListNode(4);
//    l1->next=new ListNode(5);
    Solution solution;
    ListNode *p=solution.addTwoNumbers(l1,l2);
    while(p){
        cout<<p->val;
        p=p->next;
    }

}